/**
   child.c
   
   contains fuctions the child process should
   call after fork
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <signal.h>

#include "commands.h"
#include "server.h"
#include "child.h"
#include "lprintf.h"

static void sigalrm_handler(int signo)
{
     if (SIGALRM != signo)
     {
	  lprintf("%s:%s, error signo:%d", __FILE__,
		   __FUNCTION__, signo);
	  exit(1);
     }

     /* timeout */
     close(client_conn->cmdfd);
     close(client_conn->datafd);
     free(client_conn);

     exit(255);
}

static void sigpipe_handler(int signo)
{
     lprintf("SIGPIPE caught.\n");
     
     return;
}
void child_setsig()
{
     signal(SIGALRM, sigalrm_handler);
     //    signal(SIGPIPE, sigpipe_handler);
     signal(SIGPIPE, SIG_IGN);
     return;    
}

void child_init()
{
     client_conn->datafd_mutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t));
     if (pthread_mutex_init(client_conn->datafd_mutex, NULL))
     {
	  lprintf("%s:%s datafd mutex init error!",
		  __FUNCTION__, __LINE__);
     }

     child_setsig();
     //TODO: child connection init

      //TODO: send welcome message
     send(client_conn->cmdfd, server_conf->welcome_msg,
	  strlen(server_conf->welcome_msg), 0);

     /*    if (dup2(client_conn->cmdfd, STDOUT_FILENO) == -1)
     {
	  perror("dup2");
	  exit(1);
     }*/
     //TODO: go to cmd_parser

     //puts("what the hell");
     //  puts("stdout is redirected!");
     // fflush(stdout);
     cmd_parser();
}





